#-*- encoding: utf-8 -*-
'''
KML Document Class (kml)
'''

import os.path
from __xml__ import xml
from feat import Container

__all__ = ['kml']

class kml(Container):
    """
    This class describes the XML document and the kml root element. 
    It is a Container subclass, which means it can contain Styles and Features.  
    """
    def __init__(self, kmlFile=""):
        self.filename = kmlFile
        if not os.path.exists(kmlFile):
            self._doc = xml.getDOMImplementation().createDocument(None,"kml", None)
        else:
            self._doc = xml.parse(kmlFile)
        self._doc.documentElement.attributes["xmlns"] = "http://earth.google.com/kml/2.2"
        self._networkLinkControls = []
        self.__tagName__ = "kml"
        Container.__init__(self, id="")
    
    def addNetworkLinkControl(self, networkLinkControl):
        if not isinstance(networkLinkControl,NetworkLinkControl):
            raise TypeError(self, "kml was expecting networkLinkControl to be "+
                            "an instance of kml.NetworkLinkControl")
        else:
            self._networkLinkControls.append(networkLinkControl)
    
    def removeNetworkLinkControl(self, networkLinkControlOrIndex):
        if type(networkLinkControlOrIndex) == int or \
            isinstance(networkLinkControlOrIndex,NetworkLinkControl):
                self._networkLinkControls.remove(networkLinkControlOrIndex)
        else:
                raise TypeError(self, "kml was expecting networkLinkControl to be "+
                            "an instance of kml.NetworkLinkControl")

    def clearNetworkLinkControls(self):
        self._networkLinkControls = []  
        
    def toXmlNode(self, kml=None):
        raise AttributeError("There is nothing to see here.  Move along. ")
    
    def parseKMLNode(self, KMLNode=None):
        raise AttributeError("There is nothing to see here.  Move along. ")

    def toXmlDocument(self):
        if self._comments:
            for comment in self._comments:
                self._doc.documentElement.\
                    appendChild(self._doc.createComment(comment))
        if self._features:
            for feature in self._features:
                self._doc.documentElement.appendChild(feature.toXmlNode(self))
        if self._networkLinkControls:
            for control in self._networkLinkControls:
                self._doc.documentElement.appendChild(control.toXmlNode(self))
        return self._doc
    
    def toStr(self, pretty = False):
        theDoc = self.toXmlDocument()
        if pretty == True:
            return theDoc.toprettyxml("\t","\n","UTF-8")
        return theDoc.toxml("UTF-8")
    
    def ParseKMLDocument(self):
        Container.parseKMLNode(self, self._doc)

    def read(self, bytes=0):
        if bytes:
            return self._doc.toxml("UTF-8")[0:bytes]
        else:
            return self._doc.toxml("UTF-8")
    
    def write(self):
        if self.filename:
            handle = open(self.filename,"w")
            handle.write(self.toStr(pretty=True))
            handle.close()
        else:
            raise IOError(2, "Must specify kml.filename!")

    def close(self):
        self._doc.unlink()
        del self._doc
        del self._features
        del self._networkLinkControls
    
    

    
    